#include "calc.h"
#include <string>
#include <iostream>
#include <fstream>

using namespace std;

calc cal;

void setV() {
	string key, value;
	cout << "input key:" << flush;
	getline(cin, key);
	cout << "input value:" << flush;
	getline(cin, value);
	cal.setMap(key, value);
}

void delV() {
	string key, value;
	cout << "input key:" << flush;
	getline(cin, key);
	cal.delMap(key);
}

void hst2file() {
	string fileName;
	cout << "input file name:" << flush;
	getline(cin, fileName);
	ofstream fo(fileName.c_str());
	if (!fo) {
		return;
	}
	cal.outHistory(fo);
	fo.close();
}

void log2file() {
	string fileName;
	cout << "input file name:" << flush;
	getline(cin, fileName);
	ofstream fo(fileName.c_str());
	if (!fo) {
		return;
	}
	cal.outEveLog(fo);
	fo.close();
}

void map2file() {
	string fileName;
	cout << "input file name:" << flush;
	getline(cin, fileName);
	if (fileName.empty()) {
		cal.outMapToFile();
	} else {
		cal.outMapToFile(fileName);
	}
}

void file2map() {
	string fileName;
	cout << "input file name:" << flush;
	getline(cin, fileName);
	if (fileName.empty()) {
		cal.inMapFromFile();
	} else {
		cal.inMapFromFile(fileName);
	}
}

bool anl(string str) {
	if (str == "set") {
		setV();
		return true;
	}
	if (str == "del") {
		delV();
		return true;
	}
	if (str == "hst2file") {
		hst2file();
		return true;
	}
	if (str == "log2file") {
		log2file();
		return true;
	}
	if (str == "map2file") {
		map2file();
		return true;
	}
	if (str == "file2map") {
		file2map();
		return true;
	}if (str == "exit") {
		cout << "bye" << endl;
		exit(0);
	}
	return false;
}

int main() {
	string tempStr;
	cout << "SFCALC by SkyFire" << endl << "Version: 1.0" << endl<<endl;
	while (true) {
		try {
			cout << ">>" << flush;
			getline(cin, tempStr);
			cout << "************************************" << endl<<"------------------------------------------------------------------------" << endl;
			if (!anl(tempStr)) {
				cal.input(tempStr);
				cal.runIt();
				cal.output();
			}
		} catch (sfError &err) {
			err.output();
		} catch (...) {
			cout << "other error" << flush;
		}
		cout << endl << "------------------------------------------------------------------------"  << endl << "************************************" << endl;
	}
}